package logic

import (
	"context"
	"github.com/pkg/errors"
	"mall/app/product/model"
	"mall/common/xerr"

	"mall/app/product/cmd/rpc/internal/svc"
	"mall/app/product/cmd/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetAttrGroupInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetAttrGroupInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAttrGroupInfoLogic {
	return &GetAttrGroupInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// GetAttrGroupInfo 获取属性分组详情
func (l *GetAttrGroupInfoLogic) GetAttrGroupInfo(in *pb.GetAttrGroupInfoReq) (*pb.GetAttrGroupInfoResp, error) {
	attrGroup, err := l.svcCtx.AttrGroupModel.FindOne(l.ctx, in.AttrGroupId)
	list, err := l.svcCtx.CategoryModel.FindAll(l.ctx)
	if err != nil {
		logx.Errorf("err: %+v", err)
		return nil, errors.Wrapf(xerr.NewErrorWithCode(xerr.DbError), "err : %v", err)
	}
	categoryPath := make([]int64, 0)
	categoryPath = getParentCategory(list, attrGroup.CatelogId, categoryPath)

	return &pb.GetAttrGroupInfoResp{
		AttrGroupId:   attrGroup.AttrGroupId,
		AttrGroupName: attrGroup.AttrGroupName,
		Sort:          attrGroup.Sort,
		Description:   attrGroup.Descript,
		Icon:          attrGroup.Icon,
		CategoryId:    attrGroup.CatelogId,
		CategoryPath:  categoryPath,
	}, nil
}

func getParentCategory(list []*model.PmsCategory, categoryId int64, categoryPath []int64) []int64 {
	for _, v := range list {
		if v.CatId == categoryId {
			if v.ParentCid != 0 {
				categoryPath = append(categoryPath, getParentCategory(list, v.ParentCid, categoryPath)...)
				break
			}
		}
	}
	categoryPath = append(categoryPath, categoryId)
	return categoryPath
}
